function [S] = lc_adder(A,B)
    r = 2;
    l = 1;
    u = 1;
    P = A+B;
    len = length(P);
    S = zeros(1,len);
    t_in = 0;
    e_in = 0;
    for i = len:-1:1,
        p = P(i);
        x = A(i);
        y = B(i);
        e_out = estimation(x,y);
        [t_out,w] = transfer_interim(p,e_in);
        S(i) = w+t_in;
        t_in = t_out;
        e_in = e_out;
        W(i) = w;
        T(i) = t_out;
        E(i) = e_out;
    end
    
    if(t_out ~= 0)
        S = [t_out S];
    end
    
    lambda = ceil(l/(r-1));
    my = ceil(u/(r-1));
    fprintf('\tradix: %d\n',r);
    fprintf('\tinterval: %d,%d\n',-l,u);
    fprintf('\tlambda: %d\n',lambda);
    fprintf('\tmy: %d\n',my);
    fprintf('\t%d<=w<=%d\n',-l+lambda,u-my);
    fprintf('\t%d<=t<=%d\n',-lambda,my);
    fprintf('\ta: %s\n',mat2str(A));
    fprintf('\tb: %s\n',mat2str(B));
    fprintf('\tp: %s\n',mat2str(P));
    fprintf('\te: %s\n',mat2str(E));
    fprintf('\tt: %s\n',mat2str([T(2:end) 0]));
    fprintf('\tw: %s\n',mat2str(W));
    fprintf('\ts: %s\n',mat2str(S));
end

function e_out = estimation(x,y)
    e_out = 1;
    if(x >= 0 && y >= 0)
        e_out = 0;
    end
end

function [t_out,w] = transfer_interim(p,e_in)
    r = 2;
    range = [-1 0 1];
    if(~e_in)
        range = [1 0 -1];
    end
    ok = 0;
    for t_out = range,
        w = p-r*t_out;
        if w >= -1 && w <= 1
            ok = 1;
            break;
        end
    end
    
    if ok == 0
       fprintf('failed to find a good t, t:%d,w:%d\n',t_out,w); 
    end
end